package com.ljm.shiro.session;

import com.google.common.collect.Sets;
import org.apache.shiro.session.Session;
import org.apache.shiro.session.mgt.eis.AbstractSessionDAO;
import org.springframework.data.redis.core.RedisTemplate;

import java.io.Serializable;
import java.util.Collection;
import java.util.Set;
import java.util.concurrent.TimeUnit;

/**
 * 版权：    Copyright by ljm
 * 描述：
 * 修改人：  HuamingChen
 * 修改时间：2018/12/12
 * 跟踪单号：
 * 修改单号：
 * 修改内容：
 */
public class RedisSessionDao extends AbstractSessionDAO {
    // Session超时时间，单位为毫秒
    private long expireTime = 120000;
    /**
     * 缓存
     */
    private RedisTemplate<String, Object> redisTemplate;
    /**
     * 缓存前缀
     */
    private String prefix = "shiro:session";

    public RedisSessionDao() {
        super();
    }

    public RedisSessionDao(long expireTime, RedisTemplate<String, Object> redisTemplate) {
        super();
        this.expireTime = expireTime;
        this.redisTemplate = redisTemplate;
    }

    @Override
    protected Serializable doCreate(Session session) {
        Serializable sessionId = this.generateSessionId(session);
        this.assignSessionId(session, sessionId);
        redisTemplate.opsForHash().put(prefix, session.getId(), session);
        redisTemplate.expire(prefix + session.getId(), expireTime, TimeUnit.MILLISECONDS);
        return sessionId;
    }

    @Override
    protected Session doReadSession(Serializable sessionId) {
        if (sessionId == null) {
            return null;
        }
        return (Session) redisTemplate.opsForHash().get(prefix, sessionId);
    }

    @Override
    public void update(Session session){
        if (session == null || session.getId() == null) {
            return;
        }
        session.setTimeout(expireTime);
        redisTemplate.opsForHash().put(prefix, session.getId(), session);
        redisTemplate.expire(prefix + session.getId(), expireTime, TimeUnit.MILLISECONDS);
    }

    @Override
    public void delete(Session session) {
        if (null == session) {
            return;
        }
        redisTemplate.opsForHash().delete(prefix, session.getId());
    }

    @Override
    public Collection<Session> getActiveSessions() {
        Set<Object> sessions = redisTemplate.opsForHash().keys(prefix);
        Set<Session> sessionSet = Sets.newHashSet();
        if (sessions != null) {
            for (Object obj : sessions) {
                sessionSet.add((Session) obj);
            }
        }
        return sessionSet;
    }

}
